#pragma once
#include"ThreadCache.h"
#include"PageCache.h"
#include"ObjectPool.h"

static void* ConcurrentAlloc(size_t size)
{
	if (size > MAX_BYTES)
	{
		//大于256Kb，256Kb/8Kb=32
		//32<页<=128,直接向PageCache申请；页>128，直接向堆申请
		size_t alignSize = AMSize::RoundUp(size);//获取对齐大小
		size_t kpage = alignSize >> PAGE_SHIFT;//获取页数

		PageCache::GetInstance()->_pageMtx.lock();
		Span* span=PageCache::GetInstance()->NewSpan(kpage);
		span->_objSize = size;//(大于256kb)存储对象大小
		PageCache::GetInstance()->_pageMtx.unlock();

		void* ptr = (void*)(span->_pageId << PAGE_SHIFT);
		return ptr;
	}
	else
	{
		if (TLS_ThreadCache == nullptr)
		{
			//TLS_ThreadCache = new ThreadCache;
			static ObjectPool<ThreadCache>tcPool;
			TLS_ThreadCache = tcPool.New();
		}
		//cout << std::this_thread::get_id() << ";" << TLS_ThreadCache << endl;
		return TLS_ThreadCache->Allocate(size);
	}
}

static void ConcurrentFree(void* ptr)
{
	Span* span = PageCache::GetInstance()->MapObjToSpan(ptr);//通过映射关系找到span
	size_t size = span->_objSize;
	if (size > MAX_BYTES)
	{
		PageCache::GetInstance()->_pageMtx.lock();
		PageCache::GetInstance()->ReleaseSpanToPageCache(span);//释放内存
		PageCache::GetInstance()->_pageMtx.unlock();
	}
	else
	{
		assert(TLS_ThreadCache);
		TLS_ThreadCache->Deallocate(ptr, size);
	}
}